#include <unistd.h>
#include <signal.h>
#include <cstring>
#include "Thread.h"
#include "debug.h"

volatile unsigned int Thread::uniqueID = 0;

Thread::Thread( const std::string & name ) : m_tid(0), running(false)
{
	Entry::id = ++uniqueID;
	strncpy(Entry::name, name.c_str(), Entry::MAXNAMESIZE);
#ifndef CHINESE
	debug("creat thread but not run, id %u, %.*s", Entry::id, Entry::MAXNAMESIZE, Entry::name);
#else
	debug("预备一个线程, id %u, %.*s", Entry::id, Entry::MAXNAMESIZE, Entry::name);
#endif
	//threadmanager.addthread(this);
}

Thread::~Thread()
{
#ifndef CHINESE
	debug("delete thread id %u, %.*s", Entry::id, Entry::MAXNAMESIZE, Entry::name);
#else
	debug("删除一个线程, id %u, %.*s", Entry::id, Entry::MAXNAMESIZE, Entry::name);
#endif
}

void * Thread::threadFunc(void * arg)
{
	Thread * r = (Thread *) arg;
	r->running = true;
	r->mutex.unlock();

	//mask all signals
	sigset_t mask;
	sigfillset(&mask);
	pthread_sigmask(SIG_SETMASK, &mask, NULL);

	// for rand_r(unsigned int * seed)
	r->seed = time(NULL);
	r->run();

	r->mutex.lock();
	r->running = false;
	r->mutex.unlock();

	::pthread_exit(NULL);
	return NULL;
}

unsigned int Thread::sleep( unsigned int seconds)
{
	return ::sleep(seconds);
}

unsigned int Thread::msleep( unsigned int mSeconds)
{
	return ::usleep(mSeconds * 1000U);
}

bool Thread::start()
{
	mutex.lock();
	if ( !running )
	{
		if ( ::pthread_create(&m_tid, NULL, threadFunc, this ) )
		{
			mutex.unlock();
			return false;
		}
	}
	else
	{
		mutex.unlock();
	}
#ifndef CHINESE
	debug("Run thread id %u, %.*s", Entry::id, Entry::MAXNAMESIZE, Entry::name);
#else
	debug("启动线程id %u, %.*s", Entry::id, Entry::MAXNAMESIZE, Entry::name);
#endif
	return true;
}

void Thread::join() const
{
	if ( m_tid != 0 )
		::pthread_join(m_tid, NULL);
}

